package cshi.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


//lock,condition只有在更加困难的多线程问题中才是必需的，一般就用wait和notify
class Car2 {
	private boolean waxOn = false;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	
	public void waxed(){
		//对每个Lock的调用都紧跟try-finally，保证所有情况下都可以释放锁
		lock.lock();
		try {
			waxOn = true;//ready to buff
			condition.signalAll();
		} finally {
			// TODO: handle finally clause
			lock.unlock();
		}

	}
	
	public void buffed(){
		lock.lock();
		try {
			waxOn = false;
			condition.signalAll();//ready for another coat of wax
		} finally {
			// TODO: handle finally clause
			lock.unlock();
		}
	}
	
	public void waitForWaxing() throws InterruptedException{
		lock.lock();
		try {
			while (waxOn == false)
				condition.await();
		} finally {
			// TODO: handle finally clause
			lock.unlock();
		}
	}
	
	public void waitForBuffing() throws InterruptedException{
		lock.lock();
		try {
			while (waxOn == true)
				condition.await();
		} finally {
			// TODO: handle finally clause
			lock.unlock();
		}
	}
}

class WaxOn2 implements Runnable{
	private Car2 car;
	public WaxOn2(Car2 c) {
		// TODO Auto-generated constructor stub
		car = c;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (!Thread.interrupted()){
				System.out.println("wax on");
				TimeUnit.MILLISECONDS.sleep(200);//模拟上蜡的时间
				car.waxed();
				car.waitForBuffing();//上蜡之后等待抛光
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("waxon interrupt");
		}
	}
	
}

class WaxOff2 implements Runnable{
	private Car2 car;
	public WaxOff2(Car2 c) {
		// TODO Auto-generated constructor stub
		car = c;
	}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			while (!Thread.interrupted()){
				car.waitForWaxing();//等待上蜡
				System.out.println("wax off");
				TimeUnit.MILLISECONDS.sleep(200);
				car.buffed();//上蜡成功后就抛光
			}
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("waxoff interrupt");
		}
	}
}

public class ConditionAndSignal {
	public static void main(String[] args) throws InterruptedException {
		// TODO Auto-generated method stub
		Car2 car = new Car2();
		ExecutorService es = Executors.newCachedThreadPool();
		es.execute(new WaxOff2(car));
		es.execute(new WaxOn2(car));
		TimeUnit.SECONDS.sleep(5);
		es.shutdownNow();//interrupt all tasks
	}
}
